package com.yuan.j2ee.thread.learn01;


import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/***
 * 两个线程，一个输出字母，一个输出数字，交替输出1A2B3C4D...26Z。
 * 利用PipedInputStream管道流实现（效率低）
 * @author 徐恩源
 * @date 2020-01-17 10:14:46
 */
public class T10_PipedStream {
    public static void main(String[] args) throws IOException {
        char[] aI = "1234567".toCharArray();
        char[] aC = "ABCDEFG".toCharArray();
        PipedInputStream input1 = new PipedInputStream();
        PipedInputStream input2 = new PipedInputStream();
        PipedOutputStream output1 = new PipedOutputStream();
        PipedOutputStream output2 = new PipedOutputStream();

        input1.connect(output2);;
        input2.connect(output1);

        String msg = "Your Turn";

        new Thread(() -> {
            byte[] buffer = new byte[9];
            try {
                for (char c : aI) {
                    input1.read(buffer);
                    if (new String(buffer).equals(msg)){
                        System.out.print(c);
                    }
                    output1.write(msg.getBytes());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            byte[] buffer = new byte[9];
            try {
                for (char c : aC) {

                    System.out.print(c);

                    output2.write(msg.getBytes());

                    input2.read(buffer);
                    if (new String(buffer).equals(msg)) {
                        continue;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

}
